package validators;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import javax.faces.application.FacesMessage;
import javax.faces.component.UIComponent;
import javax.faces.component.UIInput;
import javax.faces.context.FacesContext;
import javax.faces.validator.Validator;
import javax.faces.validator.ValidatorException;

import dataStorage.DBData;

import beans.User;

public class LoginValidator implements Validator{

	@Override
	public void validate(FacesContext arg0, UIComponent arg1, Object arg2) throws ValidatorException {
		User u = (User)arg0.getExternalContext().getSessionMap().get("userBean");
		UIInput ui = (UIInput) arg1.findComponent("headerForm:logName");
		String username = (String) ui.getValue();
		String password = (String)arg2;
		if (username.length() == 0){
			FacesMessage fm = new FacesMessage(FacesMessage.SEVERITY_ERROR, "sadasd", "sdadas");
			u.setLoggedIn(false);
			throw new ValidatorException(fm);
		}
		if (password.length() == 0){
			FacesMessage fm = new FacesMessage(FacesMessage.SEVERITY_ERROR, "Password empty!", "Password empty!");
			u.setLoggedIn(false);
			throw new ValidatorException(fm);

		}
		username = username.toLowerCase().trim();

		Connection connection = null;
		try {
			connection = DBData.getConnection();
		} catch (ClassNotFoundException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		} catch (SQLException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
		
		String valQuery = "SELECT * FROM ZUSER WHERE (UNAM = '" + username + "')";
		try {
			PreparedStatement ps = connection.prepareStatement(valQuery);
			ResultSet rs = ps.executeQuery();
			FacesMessage fm = new FacesMessage(FacesMessage.SEVERITY_ERROR, "Username or password is wrong", "Username or password is wrong");
			if (!rs.next()) {
				u.setLoggedIn(false);
				throw new ValidatorException(fm);
			} else {
				String realPassword = rs.getString(3);
				System.out.println(realPassword + " " + password);
				u.setID(rs.getInt(1));
				if (!realPassword.equals(password)){
					u.setLoggedIn(false);
					throw new ValidatorException(fm);	
				}
			}
		} catch (SQLException e) {
			e.printStackTrace();
			u.setLoggedIn(false);
			throw new ValidatorException(new FacesMessage("SQLException"));
		}
		u.setLoggedIn(true);
	}

}
